package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.properties.AliOssProperties;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口,文件上传")
public class CommonController {
//    @Autowired
//    private AliOssProperties aliOssProperties;
    @Autowired
    private AliOssUtil aliOssUtil;
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(@RequestPart MultipartFile file){
        log.info("文件上传：{}",file);
            //获取文件原始文件名 100.jpg
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀   dfdfdf.png
            int index = originalFilename.lastIndexOf(".");
            String suffix = originalFilename.substring(index);
            String newFileName = UUID.randomUUID().toString() + suffix;
//            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
//            //构造新文件名称,UUID生成字符串当作文件名
//            String objectName = UUID.randomUUID().toString() + extension;

            //文件的请求路径
//            AliOssUtil aliOssUtil = new AliOssUtil(aliOssProperties.getEndpoint(), aliOssProperties.getAccessKeyId(), aliOssProperties.getAccessKeySecret(), aliOssProperties.getBucketName());
            try {
                String fileurl = aliOssUtil.upload(file.getBytes(), newFileName);
                return Result.success(fileurl);
            } catch (IOException e) {
                return Result.error("文件上传失败");
            }
//            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
//            return Result.success(filePath);
//        } catch (IOException e) {
//            log.error("文件上传失败：{}", e);
//        }}


    }
}
